package com.hy.utils;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletContext;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

@ServerEndpoint("/websocket")
public class MyWebSocketEndpoint {

    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
    @OnOpen
    public void onOpen(Session session) {
        try {
            session.getBasicRemote().sendText("WebSocket Connected"); // 连接建立时发送消息
            // 将新的Session添加到sessions中
            sessions.add(session);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String jsonMessage, Session senderSession) {
        try {
            Jsonb jsonb = JsonbBuilder.create();
            MessageUtils message = jsonb.fromJson(jsonMessage, MessageUtils.class);

            if (message.getId() != null) {
                // 将 MessageUtils 对象转换为 JSON 字符串
                String jsonstr = jsonb.toJson(message);

                // 广播消息给所有连接的客户端
                for (Session session : sessions) {
                    if (!session.equals(senderSession)) {
                        // 发送 JSON 字符串
                        session.getBasicRemote().sendText(jsonstr);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        // 当连接关闭时，将对应的Session从sessions中移除
        sessions.remove(session);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
    }
}
